<?php
namespace App\DBs;

use Illuminate\Support\Facades\DB;

class SlideCodeDB extends BaseDB
{
    /**
     * 验证码滑块
     */

    protected $tSlideCode = 'slide_code';
    protected $tSlideStamp = 'slide_stamp';

    public function __construct()
    {
    }

    /**
     * 新增初始化
     */
    public function setAdd($stamp,$url,$w)
    {
        //开启事务
        DB::beginTransaction();
        try {
            DB::table($this->tSlideCode)->insertGetId(['stamp'=>$stamp,
                'markBgUrl'=>$url, 'toW'=>$w, 'created_at' => time()]);
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功');
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }

    /**
     * 验证
     * @param $stamp 时间戳标识，$w验证距离，$fault容错值
     */
    public function setCheck($stamp,$w,$fault)
    {
        $slides = DB::table($this->tSlideCode)->where('stamp',$stamp)->orderBy('id','desc')->get();
        $slideOne = count($slides) ? $this->jsonToArr($slides[0]) : '';
        if (!$slideOne) { return array('code'=>'-1', 'msg'=>'没有数据'); }
        $id = $slideOne['id']; $originW = $slideOne['toW'];
        $total = DB::table($this->tSlideStamp)->where('stamp',$stamp)
            ->where('slide',$id)->where('status',1)->count();
        if ($total>=10) { return array('code'=>'-2', 'msg'=>'验证失败已达10次'); }
        $faultMin = $originW - $fault - 1; $faultMax = $originW + $fault + 1;
        $check = ($w>$faultMin && $w<$faultMax) ? 2 : 1;
        //开启事务
        DB::beginTransaction();
        try {
            $createTime = time();
            DB::table($this->tSlideStamp)->insertGetId(['stamp'=>$stamp, 'slide'=>$id,
                'toW'=>$w, 'status'=>$check, 'created_at'=>time()]);
            //提交事务
            DB::commit();
            return array('code'=>'0', 'msg'=>'操作成功', 'result'=>$check);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>'-1', 'msg'=>'操作失败：'.$e);
        }
    }
}